import axios from 'axios';
import { message, Modal } from 'ant-design-vue';
import { useStore } from '../store/index';
import router from '../router';

const getToken = () => {
  return localStorage.getItem('token');
};

// 创建axios实例
const service = axios.create({
  baseURL: 'http://124.221.221.79:8025/api',
  timeout: 10000,
  headers: {'X-UC-SERVER': 'jestic-account'}
});

// 请求拦截器
service.interceptors.request.use(
  config => { 
    const token = getToken();
    if(token) {
      config.headers['X-USER'] = "USP " + token;
    }
    config.headers['X-GATEWAY-SERVER'] = config.url?.split('/')[0];
    return config;
  },
  error => {
    console.error('请求拦截器错误:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  response => {    
    const res = response.data;
    if(res.code === '200') {
      return res.data;
    } else {
      let isMobileFlag = isMobile();
      if (isMobileFlag) {
        doNotification('系统提示', res.message);
      } else {
        message.error(res.message || '业务错误');
      }
      return Promise.reject(new Error(res.message || '业务错误'));
    }
  },
  error => {
    console.error('响应错误:', error);
    let message = '';
    if (!error.response) {
      message = '网络连接错误';
      return Promise.reject(new Error(message));
    }
    const status = error.response.status;
    switch (status) {
      case 401:
        message = "Token过期";
        store.dispatch("logout").finally(() => location.reload());
        Modal.error({
          title: '提示',
          content: message,
          onOk: () => {
            localStorage.clear();
            window.location.reload();
            router.push({ path: "/login" });
          }
        });
        break;
      case 403:
        message = "登录已过期，请重新登录";
        Modal.error({
          title: '提示',
          content: message,
          onOk: () => {
            localStorage.clear();
            window.location.reload();
            router.push({ path: "/login" });
            console.log('登录已过期，请重新登录');
          }
        });
        break;
      case 404:
        message = "请求地址错误";
        break;
      case '500':
        message = "系统开了小差...";
        break;
      default:
        message = "网络错误";
        break;
    }
    let isMobileFlag = isMobile();
    if (isMobileFlag) {
      doNotification('系统提示', message);
    } else {
      message.error(message);
    }
    return Promise.reject(error);
  }
);

const isMobile = () => {
  let userAgentInfo = navigator.userAgent;
  let mobileKeywords = [
    'Android',
    'iPhone',
    'SymbianOS',
    'Windows Phone',
    'iPad',
    'iPod',
  ];
  return mobileKeywords.some(i => userAgentInfo.includes(i));
};

export default service;